<template>
  <el-dialog
    v-model="visible"
    title="测试用例详情"
    width="1400px"
    class="test-case-view-dialog"
    :close-on-click-modal="false"
    align-center
    destroy-on-close
  >
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="testCase" class="dialog-content">
      <div class="form-layout">
        <!-- 左侧主要内容区域 -->
        <div class="main-content">
          <!-- 标题 -->
          <div class="content-section">
            <div class="test-case-title">
              <h2>{{ testCase.title }}</h2>
              <div class="test-case-tags">
                <el-tag 
                  :color="getTestCaseStatusColor(testCase.status || 'design')"
                  size="small"
                  effect="light"
                >
                  {{ getTestCaseStatusLabel(testCase.status || 'design') }}
                </el-tag>
                <el-tag 
                  :color="getTestCasePriorityColor(testCase.priority || 'medium')"
                  size="small"
                  effect="light"
                >
                  {{ getTestCasePriorityLabel(testCase.priority || 'medium') }}
                </el-tag>
                <el-tag size="small">{{ getTestCaseTypeLabel(testCase.type || 'functional') }}</el-tag>
                <el-tag type="info" size="small">{{ getTestCaseCategoryLabel(testCase.category || 'positive') }}</el-tag>
              </div>
            </div>
          </div>

          <!-- 测试用例内容 -->
          <div class="content-section">
            <div class="section-header">
              <span class="section-label">测试用例内容</span>
            </div>
            <div class="test-case-content" v-html="formattedContent"></div>
          </div>

          <!-- 关联信息（移到左侧） -->
          <div class="content-section">
            <div class="section-header">
              <el-icon><Link /></el-icon>
              <span class="section-label">关联信息</span>
            </div>
            <div class="association-info-grid">
              <div class="association-info-item" v-if="testCase.requirement_id">
                <div class="info-item-header">
                  <el-icon><Document /></el-icon>
                  <span class="info-item-label">关联需求</span>
                </div>
                <div class="info-item-value">
                  <el-link 
                    v-if="testCase.requirement_name"
                    type="primary" 
                    @click="handleViewRequirement(testCase.requirement_id)"
                    :underline="false"
                  >
                    {{ testCase.requirement_name }}
                  </el-link>
                  <span v-else class="empty-value">-</span>
                </div>
              </div>
              <div class="association-info-item" v-if="testCase.task_id">
                <div class="info-item-header">
                  <el-icon><List /></el-icon>
                  <span class="info-item-label">关联任务</span>
                </div>
                <div class="info-item-value">
                  <span>{{ testCase.task_name || '-' }}</span>
                </div>
              </div>
              <div class="association-info-item" v-if="testCase.defect_id">
                <div class="info-item-header">
                  <el-icon><Warning /></el-icon>
                  <span class="info-item-label">关联缺陷</span>
                </div>
                <div class="info-item-value">
                  <el-link 
                    v-if="testCase.defect_name"
                    type="primary" 
                    @click="handleViewDefect(testCase.defect_id)"
                    :underline="false"
                  >
                    {{ testCase.defect_name }}
                  </el-link>
                  <span v-else class="empty-value">-</span>
                </div>
              </div>
              <div class="association-info-item" v-if="testCase.version_id">
                <div class="info-item-header">
                  <el-icon><CollectionTag /></el-icon>
                  <span class="info-item-label">关联版本</span>
                </div>
                <div class="info-item-value">
                  <el-link 
                    v-if="testCase.version_name || testCase.version_number"
                    type="primary" 
                    @click="handleViewVersion(testCase.version_id)"
                    :underline="false"
                  >
                    {{ testCase.version_number && testCase.version_name 
                      ? `${testCase.version_number} - ${testCase.version_name}` 
                      : (testCase.version_number || testCase.version_name || '-') }}
                  </el-link>
                  <span v-else class="empty-value">-</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧侧边栏 -->
        <div class="sidebar-content">
          <!-- 基本信息 -->
          <div class="sidebar-section">
            <div class="section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
            <div class="info-item">
              <span class="info-label">项目：</span>
              <span class="info-value">{{ testCase.project_name || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">负责人：</span>
              <span class="info-value">{{ testCase.assignee_name || '未分配' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建人：</span>
              <span class="info-value">{{ testCase.creator_name || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ formatDateTime(testCase.created_at) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">更新时间：</span>
              <span class="info-value">{{ formatDateTime(testCase.updated_at) }}</span>
            </div>
          </div>

          <!-- 执行统计 -->
          <div class="sidebar-section">
            <div class="section-header">
              <el-icon><DataAnalysis /></el-icon>
              <span>执行统计</span>
            </div>
            <div class="info-item">
              <span class="info-label">执行次数：</span>
              <span class="info-value">{{ testCase.execution_count || 0 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">通过率：</span>
              <span class="info-value">
                {{ testCase.pass_rate !== null && testCase.pass_rate !== undefined 
                  ? `${testCase.pass_rate.toFixed(1)}%` 
                  : '-' }}
              </span>
            </div>
            <div class="info-item" v-if="testCase.last_execution_result">
              <span class="info-label">最后结果：</span>
              <el-tag :type="getExecutionResultType(testCase.last_execution_result)" size="small">
                {{ getExecutionResultLabel(testCase.last_execution_result) }}
              </el-tag>
            </div>
            <div class="info-item" v-if="testCase.last_execution_date">
              <span class="info-label">最后执行：</span>
              <span class="info-value">{{ formatDateTime(testCase.last_execution_date) }}</span>
            </div>
          </div>

          <!-- 项目信息 -->
          <div class="sidebar-section">
            <div class="section-header">
              <el-icon><FolderOpened /></el-icon>
              <span>项目信息</span>
            </div>
            <div class="info-item" v-if="testCase.project_id">
              <span class="info-label">所属项目：</span>
              <el-link 
                v-if="testCase.project_name"
                type="primary" 
                @click="handleViewProject(testCase.project_id)"
                :underline="false"
              >
                {{ testCase.project_name }}
              </el-link>
              <span v-else class="info-value">-</span>
            </div>
          </div>

          <!-- 其他信息 -->
          <div class="sidebar-section">
            <div class="section-header">
              <el-icon><EditPen /></el-icon>
              <span>其他信息</span>
            </div>
            <div class="info-item" v-if="testCase.estimated_duration">
              <span class="info-label">预计时长：</span>
              <span class="info-value">{{ testCase.estimated_duration }} 分钟</span>
            </div>
            <div class="info-item" v-if="testCase.automation_status">
              <span class="info-label">自动化状态：</span>
              <span class="info-value">
                {{ testCase.automation_status === 'manual' ? '手动' : 
                   testCase.automation_status === 'automated' ? '已自动化' : 
                   testCase.automation_status === 'planned' ? '计划自动化' : testCase.automation_status }}
              </span>
            </div>
            <div class="info-item" v-if="testCase.tags && testCase.tags.length > 0">
              <span class="info-label">标签：</span>
              <div class="tags-list">
                <el-tag
                  v-for="tag in testCase.tags"
                  :key="tag"
                  size="small"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose">
          <el-icon><Close /></el-icon>
          关闭
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleEdit"
          v-if="canEdit"
        >
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Close, Edit, Document, DataAnalysis, Link, EditPen, List, Warning, CollectionTag, FolderOpened } from '@element-plus/icons-vue'

import { getTestCaseById, type TestCase } from '@/api/test-case'
import { formatDateTime } from '@/utils/date'
import { useRouter } from 'vue-router'
import { 
  getTestCaseTypeLabel,
  getTestCaseCategoryLabel,
  getTestCaseStatusLabel,
  getTestCaseStatusColor,
  getExecutionResultLabel,
  getExecutionResultType
} from '@/types/test-case'
import { useTestCasePriorities } from '@/composables/useTestCasePriorities'
import { usePermission } from '@/hooks/usePermission'
import { useUserStore } from '@/stores/user'
import { formatTestCaseToTemplate } from '@/utils/test-case-template'

interface Props {
  modelValue: boolean
  testCaseId: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'edit': []
}>()

const router = useRouter()
const loading = ref(false)
const testCase = ref<TestCase | null>(null)
const { hasPermission } = usePermission()
const userStore = useUserStore()
const { priorityOptions: testCasePriorityOptionsFromComposable, getPriorityName, getPriorityColor, fetchPriorities: fetchTestCasePriorities } = useTestCasePriorities()

// 优先级相关辅助函数
const getTestCasePriorityLabel = (value: string) => getPriorityName(value)
const getTestCasePriorityColor = (value: string) => getPriorityColor(value)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const canEdit = computed(() => {
  if (!testCase.value) return false
  return hasPermission('test_case:update') || 
         hasPermission('*') ||
         testCase.value.creator_id === (userStore.userInfo?.id || '') ||
         testCase.value.assignee_id === (userStore.userInfo?.id || '')
})

// 格式化的测试用例内容
const formattedContent = computed(() => {
  if (!testCase.value) return ''
  return formatTestCaseToTemplate({
    description: testCase.value.description,
    preconditions: testCase.value.preconditions,
    test_steps: testCase.value.test_steps || [],
    expected_result: testCase.value.expected_result,
    postconditions: testCase.value.postconditions
  })
})

const loadTestCase = async () => {
  if (!props.testCaseId) return
  
  loading.value = true
  try {
    const response = await getTestCaseById(props.testCaseId)
    if (response && response.success && response.data) {
      testCase.value = response.data
    } else {
      throw new Error(response?.message || '获取测试用例失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '加载测试用例失败')
    handleClose()
  } finally {
    loading.value = false
  }
}

watch(() => visible.value, async (val) => {
  if (val && props.testCaseId) {
    // 状态和优先级数据应该由主页面提供（通过composable共享）
    // 如果数据为空，才尝试加载（避免重复调用）
    if (testCasePriorityOptionsFromComposable.value.length === 0) {
      await fetchTestCasePriorities()
    }
    loadTestCase()
  }
})

const handleClose = () => {
  testCase.value = null
  visible.value = false
}

const handleEdit = () => {
  emit('edit')
  handleClose()
}

const handleViewProject = (projectId: string) => {
  router.push(`/projects/${projectId}`)
}

const handleViewRequirement = (requirementId: string) => {
  router.push(`/requirements?requirement_id=${requirementId}`)
}

const handleViewVersion = (versionId: string) => {
  router.push(`/versions/${versionId}`)
}

const handleViewDefect = (defectId: string) => {
  router.push(`/defects?defect_id=${defectId}`)
}
</script>

<style scoped lang="scss">
.test-case-view-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #EBEEF5;
    background: linear-gradient(to bottom, #ffffff, #FAFBFC);
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
  
  .loading-container {
    padding: 60px 40px;
    text-align: center;
  }
  
  .dialog-content {
    padding: 0;
    max-height: calc(80vh - 140px);
    overflow-y: auto;
    overflow-x: hidden;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
      
      &:hover {
        background: #a8abb2;
      }
    }
  }
  
  .form-layout {
    display: flex;
    gap: 20px;
    min-height: 400px;
  }
  
  .main-content {
    flex: 1;
    min-width: 0;
    
    .content-section {
      margin-bottom: 24px;
      transition: all 0.3s ease;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .test-case-title {
        padding: 20px;
        background: linear-gradient(135deg, #F5F7FA 0%, #FFFFFF 100%);
        border-radius: 8px;
        border: 1px solid #EBEEF5;
        margin-bottom: 20px;
        
        h2 {
          margin: 0 0 16px 0;
          font-size: 22px;
          font-weight: 600;
          color: #303133;
          line-height: 1.5;
          letter-spacing: -0.3px;
        }
        
        .test-case-tags {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
          
          .el-tag {
            border-radius: 4px;
            padding: 4px 10px;
            font-size: 12px;
            transition: all 0.2s ease;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
          }
        }
      }
      
      .section-header {
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #EBEEF5;
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          color: #409EFF;
          font-size: 18px;
        }
        
        .section-label {
          font-size: 15px;
          font-weight: 600;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;
          
          &::before {
            content: '';
            width: 3px;
            height: 16px;
            background: linear-gradient(to bottom, #409EFF, #66B1FF);
            border-radius: 2px;
          }
        }
      }
      
      .association-info-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        margin-top: 16px;
        
        .association-info-item {
          padding: 16px;
          background: #F8F9FA;
          border: 1px solid #EBEEF5;
          border-radius: 8px;
          transition: all 0.3s ease;
          
          &:hover {
            background: #FFFFFF;
            border-color: #C0C4CC;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          }
          
          .info-item-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 10px;
            
            .el-icon {
              color: #909399;
              font-size: 16px;
            }
            
            .info-item-label {
              font-size: 13px;
              font-weight: 600;
              color: #606266;
            }
          }
          
          .info-item-value {
            font-size: 14px;
            color: #303133;
            word-break: break-word;
            
            .empty-value {
              color: #C0C4CC;
            }
            
            .el-link {
              font-weight: 500;
              transition: all 0.2s ease;
              
              &:hover {
                color: #66B1FF;
              }
            }
          }
        }
      }
      
      .test-case-content {
        color: #606266;
        line-height: 1.8;
        padding: 28px;
        background: #FFFFFF;
        border: 1px solid #EBEEF5;
        border-radius: 8px;
        min-height: 300px;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;
        
        &:hover {
          box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
        }
        
        :deep(h2) {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          margin: 32px 0 16px 0;
          padding-bottom: 10px;
          border-bottom: 2px solid #409EFF;
          position: relative;
          
          &:first-child {
            margin-top: 0;
          }
          
          &::before {
            content: '';
            position: absolute;
            left: 0;
            bottom: -2px;
            width: 60px;
            height: 2px;
            background: linear-gradient(to right, #409EFF, transparent);
          }
        }
        
        :deep(h3) {
          font-size: 16px;
          font-weight: 600;
          color: #409EFF;
          margin: 20px 0 10px 0;
          padding-left: 12px;
          border-left: 3px solid #409EFF;
        }
        
        :deep(p) {
          margin: 0 0 14px 0;
          color: #606266;
          line-height: 1.8;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          strong {
            color: #303133;
            font-weight: 600;
            margin-right: 6px;
            padding: 2px 6px;
            background: #F0F9FF;
            border-radius: 3px;
          }
        }
        
        :deep(div) {
          margin-bottom: 14px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
        
        :deep(ul), :deep(ol) {
          padding-left: 28px;
          margin: 14px 0;
          
          li {
            margin-bottom: 10px;
            line-height: 1.8;
            color: #606266;
          }
        }
        
        :deep(a) {
          color: #409EFF;
          text-decoration: none;
          transition: all 0.2s ease;
          
          &:hover {
            color: #66B1FF;
            text-decoration: underline;
          }
        }
        
        :deep(code) {
          background: #F5F7FA;
          padding: 2px 6px;
          border-radius: 3px;
          font-family: 'Consolas', 'Monaco', monospace;
          font-size: 13px;
          color: #E6A23C;
        }
        
        :deep(blockquote) {
          border-left: 4px solid #409EFF;
          padding-left: 16px;
          margin: 16px 0;
          color: #909399;
          font-style: italic;
        }
      }
    }
  }
  
  .sidebar-content {
    width: 380px;
    flex-shrink: 0;
    position: sticky;
    top: 0;
    max-height: calc(80vh - 140px);
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
      
      &:hover {
        background: #a8abb2;
      }
    }
    
      .sidebar-section {
      background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
      border: 1px solid #EBEEF5;
      border-radius: 10px;
      padding: 22px;
      margin-bottom: 18px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.04);
      
      &:hover {
        box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
        border-color: #C0C4CC;
        transform: translateY(-1px);
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 22px;
        padding-bottom: 14px;
        border-bottom: 2px solid #F0F2F5;
        font-weight: 600;
        font-size: 15px;
        color: #303133;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          width: 40px;
          height: 2px;
          background: linear-gradient(to right, #409EFF, transparent);
          border-radius: 1px;
        }
        
        .el-icon {
          color: #409EFF;
          font-size: 18px;
          transition: transform 0.3s ease;
        }
        
        &:hover .el-icon {
          transform: scale(1.1);
        }
      }
      
      .info-item {
        display: flex;
        align-items: flex-start;
        padding: 14px 16px;
        margin: 0 -16px;
        border-radius: 6px;
        transition: all 0.2s ease;
        background: #FFFFFF;
        border: 1px solid transparent;
        
        &:hover {
          background: #F8F9FA;
          border-color: #E4E7ED;
        }
        
        &:not(:last-child) {
          margin-bottom: 8px;
        }
        
        .info-label {
          min-width: 100px;
          font-size: 13px;
          font-weight: 600;
          color: #909399;
          margin-right: 12px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          gap: 6px;
          
          &::before {
            content: '';
            width: 3px;
            height: 12px;
            background: #DCDFE6;
            border-radius: 2px;
            transition: background 0.3s ease;
          }
        }
        
        &:hover .info-label::before {
          background: #409EFF;
        }
        
        .info-value {
          flex: 1;
          font-size: 14px;
          color: #303133;
          word-break: break-word;
          line-height: 1.6;
          font-weight: 500;
          
          .el-link {
            font-weight: 500;
            transition: all 0.2s ease;
            
            &:hover {
              color: #66B1FF;
            }
          }
        }
      }
      
      .tags-list {
        margin-top: 8px;
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-tag {
          border-radius: 4px;
          transition: all 0.2s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid #EBEEF5;
    background: #FAFBFC;
    margin: 0 -24px -24px -24px;
    
    .el-button {
      padding: 10px 24px;
      font-size: 14px;
      border-radius: 6px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}
</style>

